<template>
  <div class="pie-chart-container" ref="pieChartContainer"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, defineProps } from 'vue';
import * as echarts from 'echarts';

// 定义接收的 props
const props = defineProps({
  chartData: {
    type: Object,
    required: true,
  },
});

// 创建图表容器引用
const pieChartContainer = ref(null);
let pieChartInstance = null;

// 渲染饼图的函数
const renderPieChart = () => {
  if (pieChartContainer.value) {
    pieChartInstance = echarts.init(pieChartContainer.value);
    const options = {
      title: props.chartData.title,
      legend: props.chartData.legend,
      tooltip: {
        trigger: 'item', // 鼠标悬停时显示提示

      },
      series: [
        {
          name: props.chartData.seriesName,
          type: 'pie',
          radius: props.chartData.radius, // 饼图半径
          center: props.chartData.center, // 将饼状图设置在左边（30%为左侧位置）
          // avoidLabelOverlap: false,
          // padAngle: 1,
          data: props.chartData.data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
          label: {
            formatter: '{b}: {c} ({d}%)', // 显示数据名称和百分比
          },
        },
      ],
      animation: true, // 启用动画
    };

    pieChartInstance.setOption(options);
  }
};

onMounted(() => {
  // 延迟初始化图表，以确保 DOM 元素已经渲染完成
  setTimeout(() => {
    renderPieChart();
  }, 200);
});

// 清理 ECharts 实例
// onBeforeUnmount(() => {
//   if (pieChartInstance) {
//     pieChartInstance.dispose();
//   }
// });
</script>

<style scoped>
.pie-chart-container {
  width: 100%;
  height: 100%; /* 让容器高度为100% */

}
</style>
